/*
 * @(#)xQuery.java   09/12/09
 * 
 * Copyright (C) 2009 Ecole des Mines d'Ales
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Contact: yulinz88@gmail.com
 *
 *
 *
 */



/**
 *
 */
package fr.ema.arch3d.jmodel.transformXML;

import net.sf.saxon.Configuration;
import net.sf.saxon.dom.DocumentWrapper;
import net.sf.saxon.query.DynamicQueryContext;
import net.sf.saxon.query.StaticQueryContext;
import net.sf.saxon.query.XQueryExpression;
import net.sf.saxon.trans.XPathException;

import org.w3c.dom.Document;

import org.xml.sax.SAXException;

import com.sun.tools.doclets.formats.html.ConfigurationImpl;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.stream.StreamResult;

/**
 * class description
 *
 * @version    version 1 nov. 2009
 * @author     Huaxi (Yulin) ZHANG
 */
public class xQuery {

    /**
     * Method description
     *
     * @param uri
     * @param dbQuery
     * @return
     * @throws IOException
     */
    public static String select(String uri, String dbQuery) throws IOException {

        // InputStream        xQuery        = new FileInputStream(new File(query));
        Document           document      = getDocument(uri);
        Configuration      configuration = new Configuration();
        StaticQueryContext context       = new StaticQueryContext(configuration, false);

        // search expression
        XQueryExpression expression = null;
        Writer           outWriter  = new StringWriter();
        StreamResult     result     = new StreamResult(outWriter);

        try {

            // expression = context.compileQuery(xQuery, "UTF-8");
            expression = context.compileQuery(dbQuery);

            DynamicQueryContext context2 = new DynamicQueryContext(configuration);

            context2.setContextItem(new DocumentWrapper(document, null, configuration));

            final Properties props = new Properties();

            props.setProperty(OutputKeys.METHOD, "xml");
            props.setProperty(OutputKeys.INDENT, "yes");

            File crSelectFile =
                new File(
                    "E://Yulin//Nime//Code//workspace//Arch3D-Model//src//main//java//fr//ema//arch3d//model//transfrom//tmp.xml");

            // execute and print result
            expression.run(context2, result, props);
        } catch (XPathException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return outWriter.toString();
    }

    // generate the file

    /**
     * Method description
     *
     * @param xml
     * @return
     */
    public static Document getDocument(String xml) {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder        builder;
        Document               document = null;

        try {
            builder  = builderFactory.newDocumentBuilder();
            document = builder.parse(xml);
        } catch (ParserConfigurationException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        document.normalize();

        return document;
    }

    /**
     * Method description
     *
     * @param cmpRoleDBUri
     * @param cmpRoles
     * @return
     * @throws IOException
     */
    public static String selectCmpRoles(String cmpRoleDBUri, String cmpRoles) throws IOException {
        String[] cmpRoleList    = cmpRoles.split(" ");
        String   selectCmpRoles = null;
        String   query          = "<componentRoles>{ ";

        for (int i = 0; i < cmpRoleList.length; i++) {
            if (i <= cmpRoleList.length - 2) {
                selectCmpRoles = "$x/name=\"" + cmpRoleList[i] + "\"" + " or";
            } else {
                selectCmpRoles = selectCmpRoles + " $x/name=\"" + cmpRoleList[i] + "\"";
            }
        }

        query = query + "for $x in //componentRole " + "where " + selectCmpRoles + " return $x } </componentRoles>";

        return select(cmpRoleDBUri, query);
    }
}
